# toolkit for match result
import sys

#sort match result by index
def sort_match_res(match_res,index=0,reverse=False):
    if len(match_res) < 2:
        return match_res
    if index == 0:
        return sorted(match_res, key=lambda x: [list(y.values()) for y in x[0]], reverse=reverse)
    else:
        return sorted(match_res, key=lambda x: x[index], reverse=reverse)

#print match result
def print_match_res(match_res, sort=False, index=0):
    if sort:
        match_res = sort_match_res(match_res, index=index)
    cnt = 0;
    for term in match_res:
        cnt = cnt + 1
        print(term)
        if cnt > 150:
            print('...')
            break
    print("Total number of match result is ", len(match_res))
    sys.stdout.flush()

#generate dict from match result
def gen_dict_from_res(res, size=None, maxcount=None):
    h = {}
    if len(res) == 0: return {}
    if len(res[0][0]) == 0: return {}
    cnt = 0
    for r in res:
        cnt += 1
        if maxcount and cnt > maxcount: break
        if size:
            term = r[0][0:size]
        else:
            term = r[0]

        for t in term:
            k = list(t.keys())[0]
            v = t[k]
            if k in h:
                h[k].append(v)
            else:
                h[k] = [v]
    return h
